package com.vn.egame.elazylite;

import java.util.ArrayList;
import java.util.List;

import android.animation.Animator;
import android.animation.Animator.AnimatorListener;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.animation.ValueAnimator.AnimatorUpdateListener;
import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.OvershootInterpolator;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;

import com.nineoldandroids.view.ViewHelper;
import com.viewpagerindicator.CirclePageIndicator;
import com.viewpagerindicator.PageIndicator;
import com.vn.egame.elazylite.adapter.FragmentAdapter;
import com.vn.egame.elazylite.fragment.BaseFragment;
import com.vn.egame.elazylite.fragment.Page2Fragment;
import com.vn.egame.elazylite.fragment.UtinitiesFragment;
import com.vn.egame.elazylite.listener.FinishListener;

import egame.libs.android.util.DebugUtils;

@SuppressLint("NewApi")
public class MainActivity extends FragmentActivity implements OnClickListener,
		FinishListener, OnGestureListener {

	private static final int INVISIBLE = 1;
	private static final int START_VISIBLE = 2;
	private static final int VISIBLE = 3;
	private static final int SWIPE_THRESHOLD_VELOCITY = 200;
	private Context mContext;
	private int height;
	private ViewPager mPager;
	private PageIndicator mIndicator;

	private LinearLayout mainLayout;

	private View blurLayout, scaleLayout;

	private ImageView btnHide;

	private ObjectAnimator bottomToTop, topToBottom;

	private GestureDetector gestureDetector;

	private float posY, newY, oldY, currentY;

	private boolean isScrollFinish;

	private AnimatorSet outAnim;

	private ObjectAnimator moveBack, scaleDown;

	private ValueAnimator scaleValueAnimator;

	private boolean isScroll;

	private float density;

	private ObjectAnimator alphaIn;

	private int state;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_main);

		density = getResources().getDisplayMetrics().density;
		scaleHeight = 200 * density;
		mContext = getApplicationContext();

		mainLayout = (LinearLayout) findViewById(R.id.main);
		btnHide = (ImageView) findViewById(R.id.btn_hide);
		// btnHide.setOnClickListener(this);

		blurLayout = (View) findViewById(R.id.blur_layout);

		scaleLayout = (View) findViewById(R.id.scale_layout);

		posY = mainLayout.getY();
		// blurLayout.setOnClickListener(this);

		height = getResources().getDisplayMetrics().heightPixels;

		gestureDetector = new GestureDetector(this);

		mPager = (ViewPager) findViewById(R.id.pager);
		mPager.setPageMargin(10);
		mPager.setOffscreenPageLimit(3);

		mIndicator = (CirclePageIndicator) findViewById(R.id.indicator);

		List<BaseFragment> fragments = new ArrayList<BaseFragment>();

		fragments.add(new UtinitiesFragment(this));
		fragments.add(new Page2Fragment());
		fragments.add(new Page2Fragment());

		FragmentAdapter mAdapter = new FragmentAdapter(
				getSupportFragmentManager(), fragments);

		mPager.setAdapter(mAdapter);
		mIndicator.setViewPager(mPager);

		bottomToTop = ObjectAnimator.ofFloat(mainLayout, "translationY",
				height, 0);
		bottomToTop.setInterpolator(new DecelerateInterpolator());
		bottomToTop.setDuration(300);

		DebugUtils.d("Kai", mainLayout.getY() + "");
		mainLayout.setVisibility(View.INVISIBLE);
		// ViewHelper.setY(mainLayout, height);
		state = INVISIBLE;
		// mainLayout.setVisibility(View.GONE);
		// blurLayout.setAlpha(0);
		// ViewHelper.setPivotY(mainLayout, height);

		// alphaIn = ObjectAnimator.ofFloat(blurLayout, "alpha", 0, 1);
		// alphaIn.setDuration(2000);
		// //
		// alphaIn.start();
		//
		// if (savedInstanceState == null)
		// new Handler().postDelayed(new Runnable() {
		//
		// @Override
		// public void run() {
		// // TODO Auto-generated method stub
		// mainLayout.setVisibility(View.VISIBLE);
		// bottomToTop.start();
		//
		// }
		// }, 50);

		// DebugUtils.d("Kai", "pos " + ViewHelper.getY(mainLayout));
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();

	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		// if (v == btnHide) {
		// outFinish(0);
		// } else if (v == blurLayout) {
		// outFinish(0);
		// }
	}

	@Override
	public void onFinishListener() {
		// TODO Auto-generated method stub
		finish();
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {

		switch (event.getAction()) {
		case MotionEvent.ACTION_CANCEL:
		case MotionEvent.ACTION_UP:

			switch (state) {
			case INVISIBLE:

				break;
			case START_VISIBLE:
				
				break;

			case VISIBLE:

				if (System.currentTimeMillis() - lastTouch < 100) {
					outFinish(0);
					return true;
				}
				if (isScrollFinish)
					outFinish(newY - posY);
				else {
					if (scale != 0) {

						if (scaleValueAnimator != null
								&& scaleValueAnimator.isRunning())
							scaleValueAnimator.cancel();

						// scaleDown = ObjectAnimator.ofFloat(scaleLayout,
						// "scaleY",
						// scale, 0);
						scaleValueAnimator = ValueAnimator.ofFloat(scale, 0);
						scaleValueAnimator.setDuration(300);
						scaleValueAnimator
								.addUpdateListener(new AnimatorUpdateListener() {

									@Override
									public void onAnimationUpdate(
											ValueAnimator animation) {
										// TODO Auto-generated method stub
										float value = ((Float) animation
												.getAnimatedValue())
												.floatValue();
										LinearLayout.LayoutParams ll = new LinearLayout.LayoutParams(
												LayoutParams.FILL_PARENT,
												(int) (value * scaleHeight));
										// ll.bottomMargin = (int) (scale *
										// scaleHeight);

										scaleLayout.setLayoutParams(ll);
									}
								});

						scaleValueAnimator.addListener(new AnimatorListener() {

							@Override
							public void onAnimationStart(Animator animation) {
								// TODO Auto-generated method stub

							}

							@Override
							public void onAnimationRepeat(Animator animation) {
								// TODO Auto-generated method stub

							}

							@Override
							public void onAnimationEnd(Animator animation) {
								// TODO Auto-generated method stub
								LinearLayout.LayoutParams ll = new LinearLayout.LayoutParams(
										LayoutParams.FILL_PARENT,
										(int) (0 * scaleHeight));
								// ll.bottomMargin = (int) (scale *
								// scaleHeight);

								scaleLayout.setLayoutParams(ll);
							}

							@Override
							public void onAnimationCancel(Animator animation) {
								// TODO Auto-generated method stub
								LinearLayout.LayoutParams ll = new LinearLayout.LayoutParams(
										LayoutParams.FILL_PARENT,
										(int) (0 * scaleHeight));
								// ll.bottomMargin = (int) (scale *
								// scaleHeight);

								scaleLayout.setLayoutParams(ll);
							}
						});
						// scaleDown.setDuration(300);

						scaleValueAnimator.start();

						scale = 1;
					} else if (newY != 0) {

						btnHide.setImageResource(R.drawable.ic_hide);
						if (moveBack != null && moveBack.isRunning())
							moveBack.cancel();
						moveBack = ObjectAnimator.ofFloat(mainLayout,
								"translationY", newY - posY, 0);

						moveBack.setDuration(300);
						moveBack.setInterpolator(new OvershootInterpolator());
						moveBack.start();
						newY = 0;
						oldY = 0;
					}
				}

				break;
			}

			return true;

		default:

		}
		return gestureDetector.onTouchEvent(event);
	}

	// class MyGestureDetector extends OnGestureListener {
	// @Override
	// public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
	// float velocityY) {
	//
	// // if (e2.getY() > e1.getY()) {
	// // outFinish();
	// // }
	//
	// return false;
	// }
	//
	// @Override
	// public boolean onDown(MotionEvent e) {
	// return true;
	// }
	//
	// @Override
	// public boolean onScroll(MotionEvent e1, MotionEvent e2,
	// float distanceX, float distanceY) {
	// // TODO Auto-generated method stub
	// DebugUtils.d("Kai", "Scroll  " + e2.getY());
	// return true;
	// }
	//
	//
	// }

	private void outFinish(float y) {

		if (alphaIn.isRunning())
			alphaIn.cancel();
		if (outAnim != null && outAnim.isRunning())
			return;

		int time = (int) (500 * (height - y) / height);
		topToBottom = ObjectAnimator.ofFloat(mainLayout, "translationY", y,
				height);

		topToBottom.setInterpolator(new DecelerateInterpolator());
		topToBottom.setDuration(time);
		topToBottom.addListener(new AnimatorListener() {

			@Override
			public void onAnimationStart(Animator arg0) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onAnimationRepeat(Animator arg0) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onAnimationEnd(Animator arg0) {
				// TODO Auto-generated method stub
				finish();
			}

			@Override
			public void onAnimationCancel(Animator arg0) {
				// TODO Auto-generated method stub

			}
		});
		// topToBottom.start();

		ObjectAnimator alpha = ObjectAnimator
				.ofFloat(blurLayout, "alpha", 1, 0);
		alpha.setDuration(time);
		// alpha.start();

		outAnim = new AnimatorSet();
		outAnim.playTogether(topToBottom, alpha);
		outAnim.start();
	}

	private long lastTouch;

	@Override
	public boolean onDown(MotionEvent e) {
		// Toast.makeText(getApplicationContext(), "OnDown Gesture",
		// 100).show();
		lastTouch = System.currentTimeMillis();
		return false;
	}

	@Override
	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
			float velocityY) {
		// Toast.makeText(getApplicationContext(), "Fling Gesture", 100).show();
		return true;
	}

	@Override
	public void onLongPress(MotionEvent e) {
		// Toast.makeText(getApplicationContext(), "Long Press Gesture", 100)
		// .show();
	}

	private boolean isScale;
	private float scale;
	private float lastY;

	private float scaleHeight;
	
	private float gocY;

	@Override
	public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
			float distanceY) {
		if (posY == 0) {
			posY = mainLayout.getY();
			mainLayout.setY(height);
			mainLayout.setVisibility(View.VISIBLE);
		}

		// DebugUtils.d("Kai", mainLayout.getY() +"");
		switch (state) {
		case INVISIBLE:
			if (e1.getY() - e2.getY() > 50 * density
					&& Math.abs(e2.getX() - e1.getX()) < 20) {
				state = START_VISIBLE;
				gocY = e1.getY();
			}
			break;
		case START_VISIBLE:
			newY = height - (e1.getY() - e2.getY());
			// mainLayout.setY(newY);
			if (newY >= posY) {
				mainLayout.setY(newY);
				lastY = e2.getY();
			} else if (newY > posY - scaleHeight && newY < posY) {
				// mainLayout.setY(posY);
				scale = Math.abs((e2.getY() - lastY)) * 0.4f / scaleHeight;

				LinearLayout.LayoutParams ll = new LinearLayout.LayoutParams(
						LayoutParams.FILL_PARENT, (int) (scale * scaleHeight));
				// ll.bottomMargin = (int) (scale * scaleHeight);

				scaleLayout.setLayoutParams(ll);
			}
			break;
		case VISIBLE:
			try {
				if (e1.getY() - e2.getY() > scaleHeight)
					return false;

				// if (posY == 0)
				// posY = height - mainLayout.getMeasuredHeight();

				newY = posY + (e2.getY() - e1.getY());

				if (newY > posY - scaleHeight && newY < posY) {

					scale = Math.abs((e2.getY() - e1.getY())) * 0.4f
							/ scaleHeight;

					LinearLayout.LayoutParams ll = new LinearLayout.LayoutParams(
							LayoutParams.FILL_PARENT,
							(int) (scale * scaleHeight));
					// ll.bottomMargin = (int) (scale * scaleHeight);

					scaleLayout.setLayoutParams(ll);
					// mainLayout.setPivotY(mainLayout.getHeight());
					// mainLayout.setScaleY(scale);
				} else {
					btnHide.setImageResource(R.drawable.ic_show);
					scale = 0;//
					if (newY > posY) {
						mainLayout.setY(newY);

						oldY = newY;
					} else {
						newY = oldY;
						mainLayout.setY(newY);
						// ViewHelper.setY(mainLayout, newY);
					}
				}

				if (e2.getY() - posY > 10 && newY > posY) {
					isScrollFinish = true;
				} else {
					isScrollFinish = false;
				}
				lastY = e2.getY();
			} catch (Exception ex) {
				outFinish(0);
			}
			break;
		}

		return false;
	}

	@Override
	public void onShowPress(MotionEvent e) {
	}

	@Override
	public boolean onSingleTapUp(MotionEvent e) {
		return true;
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		overridePendingTransition(0, 0);
	}
}
